package control.reader;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import data.base.Material;

public class MtlReader {
  private Map<String, Material> materials = new HashMap<String, Material>();
  
  private static final String NEW_MATERIAL = "newmtl";  
  private static final String TEXTURE = "map_Kd";
  private static final String COLOR = "Kd";

  private Material currentMaterial;
    
  public MtlReader(String fileName){
    try {
      FileInputStream fis = new FileInputStream(fileName);
      InputStreamReader isr = new InputStreamReader(fis);
      BufferedReader br = new BufferedReader(isr);
      String line;
      while((line = br.readLine()) != null){
        interpreteLineTokens(line.split(" "));
      }
      addCurrentMaterial();
    }
    catch (Exception e) {
      e.printStackTrace();
    }    
  }
  
  public Material getMaterial(String name){
    return materials.get(name);
  }
  
  private void interpreteLineTokens(String[] tokens){
    String command = tokens[0];
    
    if(command.equals(NEW_MATERIAL))
      readNewMaterial(tokens);
    else if(command.equals(TEXTURE))
      readTexture(tokens);
    else if(command.equals(COLOR))
      readColor(tokens);
  }
  
  private void readNewMaterial(String[] tokens){
    addCurrentMaterial();
    currentMaterial = new Material(tokens[1]);
  }
  
  private void readTexture(String[] tokens){
    currentMaterial.setTexture(tokens[1]);
  }
  
  private void readColor(String[] tokens){
    currentMaterial.setColor(new Color(
        Float.parseFloat(tokens[1]),
        Float.parseFloat(tokens[2]),
        Float.parseFloat(tokens[3])));
  }
  
  private void addCurrentMaterial(){
    if(currentMaterial != null){
      materials.put(currentMaterial.getName(), currentMaterial);
    }
  }
}
